package com.skivingcloud.report.datas.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.skivingcloud.report.datas.entity.ReportDatasetTransform;
import com.skivingcloud.report.datas.service.TransformStrategy;

@Component
public class DictTransformServiceImpl implements TransformStrategy {
    /**
     * 数据清洗转换 类型
     *
     * @return
     */
    @Override
    public String type() {
        return "dict";
    }

    /***
     * 清洗转换算法接口
     * @param def
     * @param data
     * @return
     * @throws JsonProcessingException
     * @throws JsonMappingException
     */
    @Override
    public List<JsonNode> transform(ReportDatasetTransform def, List<JsonNode> data) throws Exception{
        String transformScript = def.getTransformScript();
        if (StringUtils.isBlank(transformScript)) {
            return data;
        }
		JsonNode jsonNode = new ObjectMapper().readTree(transformScript);
		List<JsonNode> rd = new ArrayList<>();
		for(JsonNode dataDetail : data){
			ObjectNode json = (ObjectNode) dataDetail;
			Iterator<String> keys = dataDetail.fieldNames();
			while(keys.hasNext()){
				String key = keys.next();
				if (jsonNode.has(key)) {
                    if(json.hasNonNull(key)){
                        String string = jsonNode.get(key).get(json.get(key).asText()).asText();
                        if (StringUtils.isNotBlank(string)) {
                            json.put(key, string);
                        }
                    }
				}
			}
			rd.add(json);
		}
        return data;
    }
}